package stardust.core.io;


import java.io.IOException;
import java.io.InputStream;
import stardust.core.support.ByteUtils;


public class StreamArray extends InputStream
{

  private int offset;

  private byte[] data;

  public StreamArray(byte[] data)
  {
    this.offset = 0;
    this.data = data;
  }

  public StreamArray(InputStream inputStream) throws IOException
  {
    this(IOUtils.read(inputStream));
  }

  public int current()
  {
    return this.offset >= this.data.length ? IOUtils.IOS_END_OF_FILE : this.data[this.offset];
  }

  public int peek()
  {
    return this.offset + 1 >= this.data.length ? IOUtils.IOS_END_OF_FILE : this.data[this.offset + 1];
  }

  public byte[] peek(int peekLength)
  {
    return ByteUtils.subByteArray(this.data, this.offset + 1, peekLength);
  }

  public int read() throws IOException
  {
    return this.offset >= this.data.length ? IOUtils.IOS_END_OF_FILE : this.data[this.offset++];
  }

  public Character readChar() throws IOException
  {
    byte b0;
    byte b1;

    b0 = (byte) this.read();

    if (b0 < 0)
    {
      return null;
    }

    if (b0 < 0 && (b1 = (byte) this.read()) != -1)
    {
      return new String(new byte[]
      {
        b0, b1
      }).charAt(0);
    }
    else
    {
      return (char) b0;
    }
  }

  public String readLine() throws IOException
  {
    StringBuffer buffer = new StringBuffer();
    Character c;

    while ((c = this.readChar()) != null && c != '\n')
    {
      if (c != '\r')
      {
        buffer.append(c);
      }
    }

    return c != null || (c == null && buffer.length() > 0) ? buffer.toString() : null;
  }

  public String readTo(String... token) throws IOException
  {
    String buffer = "";
    Character c;

    while ((c = this.readChar()) != null)
    {
      buffer += c;

      for (int i = 0; i < token.length; i++)
      {
        if (buffer.toLowerCase().endsWith(token[i].toLowerCase()))
        {
          return buffer.substring(0, buffer.length() - token[i].length());
        }
      }
    }

    return buffer;
  }

}
